import express from 'express'
import usersRouter from './users';
import taskRouter from './task';
import categoryRouter from './category';
import carouselRouter from './carousel'
import articleRouter from './article'
import ciRouter from './ci'
import { jwtAuth } from '../utils/user-jwt';
const defualtRoute = express.Router();

// 注入认证token中间层模块
defualtRoute.use(jwtAuth);

defualtRoute.use('/api', usersRouter)
    .use('/api', taskRouter)
    .use('/api', categoryRouter)
    .use('/api', carouselRouter)
    .use('/api', articleRouter);


// 自定义统一异常处理中间件，需要放在代码最后
defualtRoute.use((err, req, res, next) => {
    console.log('err===', err)
    if(err && err.name === 'UnauthorizedError'){
        const {status = 401, message } = err;
        res.status(status).json({
            code: status,
            msg: 'token失效, 请重新登录',
            data: null
        })
    } else {
        const {output} = err || {}
        const errCode = output?.statusCode ?? 500;
        const errMsg = output?.payload?.message ?? err.message;
        const error = output?.payload?.error;
        res.status(errCode).json({
            code: errCode,
            msg: errMsg,
            error,
        })
    }
})
// defualtRoute.use('/api', loginRouter)
// /* GET home page. */
// defualtRoute.get('/', function(req, res, next) {
//   res.render('index', { title: 'Express' });
// });

module.exports = defualtRoute;
